/** @format */

import { dateFormatter } from '../utils/formatter'
import { formatInvoke } from '../utils/formatInvoke'
import {
  GetItemListByItemIdsResult,
  QueryVipinfoResult,
  GetOrderListResult,
  BenefitSendResult,
  ExtraInfo,
  ChangeCreditsinfo,
  ShopArgs,
  GoodsItemInfo,
  OrderParamsInfo,
  InstanceAppInfo,
  OnlineAppInfo,
  UpdateAppInfo,
  miniConfigAppInfo,
  IMarkInfo
} from './interface'

/**
 * 获取商品列表
 * @param context 云函数上下文
 * @param itemIds 商品列表
 * @param extrainfo 扩展字段，包含fileds，不传默认为：'detail_url,approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id,sold_quantity'
 * @param session 调用淘宝的session
 * @desc api：taobao.items.seller.list.get
 */
export const getItemListByItemIds = async (context: any, itemIds: string, extrainfo: ExtraInfo, session?: string) => {
  if (!context) {
    throw Error('参数context不能为空')
  }
  // if (!session) {
  //   throw Error('参数session不能为空');
  // }
  if (!itemIds) {
    throw Error('参数itemIds不能为空')
  }
  extrainfo.fields =
    extrainfo.fields ||
    'detail_url,approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id,sold_quantity'
  const invokeInfo = {
    api: 'taobao.items.seller.list.get',
    data: {
      session,
      ...extrainfo,
      num_iids: itemIds
    }
  }
  const result: GetItemListByItemIdsResult = await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
  return result
}

/**
 * 获取权益详情
 * @param context 云函数上下文
 * @param session 调用淘宝的session
 * @param ename 权益名
 * @param appName 示例：'promotioncenter-3000000003563313'
 * @desc api: alibaba.benefit.query
 */
export const getPrizeByEname = async (context: any, ename: string, appName: string, session?: string) => {
  if (!context) {
    throw Error('参数context不能为空')
  }
  // if (!session) {
  //   throw Error('参数session不能为空');
  // }
  if (!ename) {
    throw Error('参数ename不能为空')
  }
  if (!appName) {
    throw Error('参数appName不能为空')
  }

  const invokeInfo = {
    api: 'alibaba.benefit.query',
    data: {
      session,
      ename,
      app_name: appName,
      award_type: 1
    }
  }
  const benefitData = await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
  return benefitData
}
// interface ShopVipinfo {
//   source: string
//   activityId?: string
//   entrance?: string
// }
// /**
//  * 获取店铺会员链接
//  * @param context 云函数上下文
//  * @param extraInfo 扩展字段： 示例：{"source": "isvapp", "entrance": "duiba"}
//  * @param callbackUrl 回调地址
//  * @param session 调用淘宝的session
//  * @desc api: 'taobao.crm.member.joinurl.get'
//  */
// const getShopVipUrl = async (context: any, extraInfo: ShopVipinfo, session?: string, callbackUrl?: string) => {
//   if (!context) {
//     throw Error('参数context不能为空')
//   }
//   // if (!session) {
//   //   throw Error('参数session不能为空');
//   // }

//   const invokeInfo = {
//     api: 'taobao.crm.member.joinurl.get',
//     data: {
//       session,
//       extra_info: extraInfo,
//       callback_url: callbackUrl
//     }
//   }
//   const result = await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
//   // console.log(`taobao.crm.member.joinurl.get`, result);
// }

/**
 * 查询会员信息
 * @param context 云函数上下文
 * @param session 调用淘宝的session
 * @desc api: 'taobao.crm.member.identity.get'
 */
export const queryVipinfo = async (context: any, session?: string) => {
  if (!context) {
    throw Error('参数context不能为空')
  }
  // if (!session) {
  //   throw Error('参数session不能为空');
  // }

  const { mixNick } = context
  const invokeInfo = {
    api: 'taobao.crm.member.identity.get',
    data: {
      session,
      mix_nick: mixNick
    }
  }
  const result: QueryVipinfoResult = await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
  // console.log(`taobao.crm.member.identity.get`, result);
  return result
}

/**
 * 查询积分
 * @param context
 * @param session
 */
export const queryCredits = async (context: any, session?: string) => {
  if (!context) {
    throw Error('参数context不能为空')
  }
  const { mixNick } = context
  const invokeInfo = {
    api: 'taobao.crm.point.available.get',
    data: {
      session,
      mix_nick: mixNick
    }
  }
  const result: { result: number } = await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
  console.log(`taobao.crm.point.available.get`, result)
  return result.result
}

/**
 * 更新积分
 * @param context
 * @param session
 * @param options
 * @desc api: 'taobao.crm.point.change'
 */
export const changeCredits = async (context: any, options: ChangeCreditsinfo, session?: string) => {
  if (!context) {
    throw Error('参数context不能为空')
  }

  const { mixNick, env } = context
  const { quantity, change_type = 1, remark = `参与活动`, account_date, need_account_date = false } = options
  let { opt_type } = options
  if (!opt_type) {
    opt_type = '0'
  }
  const data = {
    session,
    quantity /** 积分数量, 每次变更的数量 */,
    change_type /**  变更类型：0交易，1：互动活动，2：权益兑换，3：手工调整 */,
    opt_type /** 操作类型，0：增加，1：扣减 */,
    remark /** 备注 */,
    mix_nick: mixNick,
    account_date
  }
  if (!account_date || (env === 'online' && !need_account_date)) {
    delete data.account_date
  }

  const invokeInfo = {
    api: 'taobao.crm.point.change',
    data
  }
  const result: { record_id: string } = await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
  console.log(`taobao.crm.point.change`, result)
  return result
}

interface BenifitInfo {
  right_ename: string
  receiver_id: string
  unique_id: string
  app_name: string
  session?: string
}

/**
 * 发放权益
 * @param context
 * @param args
 * @desc api: 'alibaba.benefit.send'
 */
export const benefitSend = async (context: any, args: BenifitInfo) => {
  const { right_ename, receiver_id, app_name, session } = args
  let { unique_id } = args
  if (!context) {
    throw Error('参数context不能为空')
  }
  if (!right_ename) {
    throw Error('参数right_ename(权益名)不能为空')
  }
  if (!receiver_id) {
    throw Error('参数receiver_id(接收者)不能为空')
  }
  if (!app_name) {
    throw Error('参数app_name不能为空')
  }
  // if (!session) {
  //   throw Error('参数session不能为空')
  // }
  if (!unique_id) {
    unique_id = Date.now().toString()
  }
  const invokeInfo = {
    api: 'alibaba.benefit.send',
    data: {
      right_ename,
      receiver_id,
      user_type: 'taobao',
      unique_id,
      app_name,
      session
    }
  }
  const result: BenefitSendResult = await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
  console.log(`alibaba.benefit.send`, result)
  return result
}

/**
 * 获取商家信息
 * @param context
 * @param args 包含fields字段，不传默认为'sid,title,pic_path'
 * @desc api: 'taobao.shop.seller.get'
 */
export const getShopInfo = async (context: any, args: ShopArgs) => {
  const { fields, session } = args
  if (!context) {
    throw Error('参数context不能为空')
  }
  // if (!session) {
  //   throw Error('参数session不能为空');
  // }

  const invokeInfo = {
    api: 'taobao.shop.seller.get',
    data: {
      fields: fields || 'sid,title,pic_path',
      session
    }
  }
  return await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
}

// 商品默认获取字段
const GOODS_DEFAULT_TYPE =
  'detail_url,approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id,sold_quantity'

/**
 * 获取商家在售商品列表
 * @param context
 * @param args
 * @desc api: 'taobao.items.onsale.get'
 */
export const getItemListOnSale = async (context: any, args: GoodsItemInfo) => {
  const { fields, pageNo = 1, pageSize = 10, session, title = '' } = args
  if (!context) {
    throw Error('参数context不能为空')
  }
  // if (!session) {
  //   throw Error('参数session不能为空');
  // }

  const invokeInfo = {
    api: 'taobao.items.onsale.get',
    data: {
      fields: fields || GOODS_DEFAULT_TYPE,
      page_no: pageNo,
      page_size: pageSize,
      q: title,
      session
    }
  }
  return await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
}

/**
 * 得到当前会话用户库存中的商品列表
 * @param context
 * @param args
 */
export const getItemListInStock = async (context: any, args: GoodsItemInfo) => {
  const { fields, pageNo = 1, pageSize = 10, session, title = '' } = args
  if (!context) {
    throw Error('参数context不能为空')
  }
  // if (!session) {
  //   throw Error('参数session不能为空');
  // }

  const invokeInfo = {
    api: 'taobao.items.inventory.get',
    data: {
      fields: fields || GOODS_DEFAULT_TYPE,
      page_no: pageNo,
      page_size: pageSize,
      q: title,
      session
    }
  }
  return await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
}

const ORDER_FIELDS = 'tid,type,status,payment,orders,rx_audit_status,pay_time'
const GOODS_TYPE = 'guarantee_trade,auto_delivery,ec,cod,step'
const THREE_MONTH_TIME = 60 * 60 * 24 * 30 * 3 * 1000

/**
 * 获取用户购买列表
 * @param context
 * @param args
 * @desc api: 'taobao.open.trades.sold.get'
 *
 */
export const getBuyerOrderList = async (context: any, args: OrderParamsInfo) => {
  const {
    fields = ORDER_FIELDS,
    startTime,
    endTime,
    pageNo = 1,
    pageSize = 100,
    session,
    status = '',
    type = GOODS_TYPE,
    useNext = false,
    openId
  } = args
  if (!context) {
    throw Error('参数context不能为空')
  }
  // if (!session) {
  //   throw Error('参数session不能为空');
  // }
  if (!openId) {
    throw Error('参数openId不能为空')
  }

  const invokeInfo = {
    api: 'taobao.open.trades.sold.get',
    data: {
      fields,
      status,
      session,
      type,
      start_created: startTime || dateFormatter(new Date(Date.now() - THREE_MONTH_TIME)),
      end_created: endTime || dateFormatter(new Date()),
      page_no: pageNo,
      page_size: pageSize,
      use_has_next: useNext,
      buyer_open_id: openId
    }
  }
  const result: GetOrderListResult = await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
  console.log(`taobao.open.trades.sold.get`, result)
  return result
}

/**
 * 小程序模板实例化
 * @param context
 * @param args
 * @desc api: 'taobao.miniapp.template.instantiate'
 */
export const getTemplateInstantiate = async (context: any, args: InstanceAppInfo) => {
  const {
    description,
    ext_json = { name: 'online' },
    icon,
    name,
    session,
    clients = 'taobao,tmall',
    template_id,
    template_version
  } = args
  if (!context) {
    throw Error('参数context不能为空')
  }
  // if (!session) {
  //   throw Error('参数session不能为空');
  // }
  if (!icon) {
    throw Error('参数icon不能为空')
  }
  if (!name) {
    throw Error('参数name不能为空')
  }
  if (!template_id) {
    throw Error('参数template_id不能为空')
  }
  if (!template_version) {
    throw Error('参数template_version不能为空')
  }
  if (!description) {
    throw Error('参数description不能为空')
  }

  const invokeInfo = {
    api: 'taobao.miniapp.template.instantiate',
    data: {
      description,
      ext_json,
      icon,
      name,
      clients,
      template_id,
      template_version,
      session
    }
  }
  return await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
}

/**
 * 实例化小程序上线
 * @param context
 * @param args
 */
export const pushInstanceOnline = async (context: any, args: OnlineAppInfo) => {
  const { app_id, app_version, session, clients = 'taobao,tmall', template_id, template_version } = args
  if (!context) {
    throw Error('参数context不能为空')
  }
  // if (!session) {
  //   throw Error('参数session不能为空');
  // }
  if (!app_id) {
    throw Error('参数napp_id不能为空')
  }
  if (!app_version) {
    throw Error('参数app_version不能为空')
  }
  if (!template_version) {
    throw Error('参数template_version不能为空')
  }
  if (!template_id) {
    throw Error('参数template_id不能为空')
  }

  const invokeInfo = {
    api: 'taobao.miniapp.template.onlineapp',
    data: {
      clients,
      app_id,
      template_id,
      template_version,
      app_version,
      session
    }
  }
  return await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
}

/**
 * 更新实例化应用
 * @param context
 * @param args
 */
export const updateMiniInstance = async (context: any, args: UpdateAppInfo) => {
  const {
    app_id,
    ext_json = { name: 'online' },
    session,
    clients = 'taobao,tmall',
    template_id,
    template_version,
    icon,
    desc,
    alias
  } = args
  if (!context) {
    throw Error('参数context不能为空')
  }
  // if (!session) {
  //   throw Error('参数session不能为空');
  // }
  if (!app_id) {
    throw Error('参数napp_id不能为空')
  }
  if (!template_version) {
    throw Error('参数template_version不能为空')
  }
  if (!template_id) {
    throw Error('参数template_id不能为空')
  }
  const data: UpdateAppInfo = {
    clients,
    app_id,
    template_id,
    template_version,
    ext_json,
    session
  }
  if (icon) {
    data.icon = icon
  }
  if (desc) {
    data.desc = desc
  }
  if (alias) {
    data.alias = alias
  }

  const invokeInfo = {
    api: 'taobao.miniapp.template.updateapp',
    data
  }
  return await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
}

/**
 * 小部件配置流转上线部署
 * @param context
 * @param args
 * @desc api: 'taobao.miniapp.app.seller.config.complete'
 *
 */
export const configMiniApp = async (context: any, args: miniConfigAppInfo) => {
  const { appId, version, session } = args
  if (!context) {
    throw Error('参数context不能为空')
  }
  // if (!session) {
  //   throw Error('参数session不能为空');
  // }
  if (!appId) {
    throw Error('参数appId不能为空')
  }
  if (!version) {
    throw Error('参数version不能为空')
  }

  const invokeInfo = {
    api: 'taobao.miniapp.app.seller.config.complete',
    data: {
      app_id: appId,
      version,
      session
    }
  }
  const result = await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
  console.log(`taobao.miniapp.app.seller.config.complete`, result)
  return result
}

/**
 * 专属下单接口标记
 * @param context
 * @param args
 * @desc api: 'taobao.opentrade.special.users.mark'
 */
export const specialItemMark = async (context: any, args: IMarkInfo) => {
  const { openId, itemId, skuId = '0', status = 'mark' } = args
  if (!context) {
    throw Error('参数context不能为空')
  }
  if (!openId) {
    throw Error('参数openId不能为空')
  }
  if (!itemId) {
    throw Error('参数itemId不能为空')
  }

  const invokeInfo = {
    api: 'taobao.opentrade.special.users.mark',
    data: {
      hit: true,
      open_user_ids: [openId],
      item_id: itemId,
      sku_id: skuId,
      status: status
    }
  }
  const result = await context.cloud.topApi.invoke(formatInvoke(invokeInfo))
  return result
}
